<?php
/*
 * @年糕妈妈
 * @功能说明：系统消息模块
 * @更新说明：暂无更新
 * @文件名 SysmsgController.class.php
 * @编码 UTF-8
 * @创建时间 2015-7-21 下午3:38:37
 * @创建人 XING
 */

namespace home\Controller;
use dg\Model\SysMsgModel;
use Think\Controller;
use Org\Util\Umeng;
class SysmsgController extends ApibaseController {
	/*
	 * 年糕妈妈_系统消息模块
	 * @date: 2015-3-31下午7:20:44
	 * @editor: XING
	 */
	public function index(){
		/*参数初始化*/
		$page = I('get.page') ?: 1;
		$perpage = 20;$url = '';
		$list = M('SysMsg');
		$url = array();
		if(I('get.msgtitle')){
			$list = $list->where('sys_msg_title LIKE "%'.I('get.msgtitle').'%"');
			$url['msgtitle'] = I('get.msgtitle');
		}
		if(I('get.msgid')){
			$list = $list->where(array('sys_msg_id'=>I('get.msgid')));
			$url['msgid'] = I('get.msgid');
		}
		$getObj = clone $list;
		$sysData = $list->order(array('sort'=>'desc'))->page($page,$perpage)->select();
		$this->assign('page',setPage($getObj->count(),$perpage,$page,'?'.http_build_query($url)));
		$this->assign('sysData',$sysData);

		$this->display("sysmsg/list");
	}

	/*
	 * @功能 添加系统消息
	 * @params null
	 * @return void
	 * @author lzm
	 */
	public function addSysMsg() {
        if(I('post.dosubmit')){
            $sys_msg_id = intval(I("post.sys_msg_id"));
            $sys_msg_pic = I("post.sys_msg_pic");
            if($sys_msg_pic{0} == '/'){
            	$sysMsgPic = $this->up_qiniu(UPLOAD_PATH.$sys_msg_pic);
            }else{
            	$sysMsgPic = $sys_msg_pic;
            }
            $data = array(
                'sys_msg_title' 	=> trim(I("post.title")),
                'type' 				=> 1,
                'sort' 				=> intval(I('post.sort')),
                'sys_msg_pic'		=> $sysMsgPic,
                'udpate_at' 		=> time(),
            );
            if(I('post.msg_type')){
            	$data['sys_msg_content'] = trim(I("post.content"));
            }else{
            	$data['sys_msg_url'] = trim(I("post.msg_url"));
            }
            if($sys_msg_id) {
            	if(I('post.msg_type')){
            		$data['sys_msg_url'] = 'https://mdata.hipaygo.cn/tmp/sysDetail?id='.$sys_msg_id;
            	}
               $res =  M("SysMsg")->where(array("sys_msg_id"=>$sys_msg_id))->setField($data);
            }else{
                $data['add_at'] = time();
                $res = M("SysMsg")->add($data);
            }
            if($res) {
            	if(I('post.msg_type')){
            		$update = ['sys_msg_url'=>'https://mdata.hipaygo.cn/tmp/sysDetail?id='.$res];
            		M("SysMsg")->where(array("sys_msg_id"=>$res))->setField($update);
            	}
                $this->showtips("操作完成");
            }
            $this->showtips("操作失败");
        }
        $id = I("get.id");
        $info = array();
        if($id) {
            $info = M("SysMsg")->where(array('sys_msg_id'=>$id))->find();

        }
        // var_dump($info);exit;
        $this->assign("info",$info);
        $this->display("sysmsg/addsysmsg");
    }

    public function up_qiniu($filePath){
//        $filePath = UPLOAD_PATH.'/upload/image/20161019/20161019161933_50525.jpg';
        $key = 'hz_'.time().'_'.rand(1000,9999);
        // 要上传文件的本地路径
        $data = (new \Org\Util\Qiniu())->upFile($filePath,$key);
        $qiniu_file_url = QINIUHOST.$data['key'];
        if($qiniu_file_url){
            unlink($filePath);
        }
        return $qiniu_file_url;
    }

    public function delmsg() {
        $sys_msg_id = intval(I("get.id"));
        if(!$sys_msg_id) {
            $this->showtips("参数错误!");
        }
        $info = M("SysMsg")->where(array('sys_msg_id'=>$sys_msg_id))->find();
        if(!$info) {
            $this->showtips("信息不存在!");
        }
        if(M("SysMsg")->where(array('sys_msg_id'=>$sys_msg_id))->delete()) {
            $this->showtips("删除完成!");
        }
        $this->showtips("删除失败!");
    }
	
	/*
	 * 年糕妈妈_添加推送
	 * @date: 2015-4-1下午3:04:01
	 * @editor: XING
	 */
	public function addmsg(){
		if(I('post.dosubmit')){
			if(in_array(I('post.ts'),array('type1','type2')) && I('post.voice_url')){
				if(I('post.ts') == 'type1' && !I('post.voice_url')){
					$this->showtips('推广语音文件必须选择');
				}else if(I('post.ts') == 'type2' && !I('post.contents')){
					$this->showtips('文本转语音内容不能为空');
				}
				$getHwares = M('HwcodeEntity')->field('maccode')
						   ->where('cust_id > 0 AND check = 1')->select();
				if($getHwares){
					foreach($getHwares AS $vals){
						switch(I('post.ts')){
							case 'type1':
								$replyWord = filesize($_SERVER['DOCUMENT_ROOT'] . '/../../statics'.I('post.voice_url')).'|'.transUrl(I('post.voice_url'));
								I('post.title') ? $replyWord = '30|'.I('post.title').'|'.$replyWord : '0||'.$replyWord;
								(new \service\imtalk\ImTalk())->sendIm(trim($vals['maccode']), 4, 3, $replyWord);
								break;
							case 'type2':
								$thisTime = time()+1000;$text = trim(I('post.contents'));$randStr = date("YmdHis").rand(10000, 99999);
								$base_path = $_SERVER['DOCUMENT_ROOT'] . '/../../statics/upload/trans/'.$randStr.'.mp3';
								$voiceData = copy('http://api.okvoice.com/tts/?apiKey=e4ecb2444614ba01568bdfd4ec95282b&expires='.$thisTime.'&format=WAV&speed=1&text='.$text.'&voice=cnfemale&signature='.hash_hmac("sha1", 'apiKey=e4ecb2444614ba01568bdfd4ec95282b&expires='.$thisTime.'&format=WAV&speed=1&text='.$text.'&voice=cnfemale', '0d84da8ba463989ad2144c152317055c'), $base_path);
								$sayWords = trim($replyWord);
								if($voiceData){
									$urlData = '/upload/trans/'.$randStr.'.mp3';
									$sayWords = '30|'.trim($replyWord).'|'.filesize($_SERVER['DOCUMENT_ROOT'] . '/../../statics/upload/trans/'.$randStr.'.mp3').'|'.transUrl($urlData);
									(new \service\imtalk\ImTalk())->sendIm(trim($vals['maccode']), 4, 3, $replyWord);
								}
								break;
							case 'type3':
								if(!I('post.texts')){
									$this->showtips('文本内容不能为空');
								}
								$replyWord = '120|'.I('post.texts').'|0|0';
								(new \service\imtalk\ImTalk())->sendIm(trim($vals['maccode']), 4, 3, $replyWord);
								break;
							default:
								break;
						}
					}
				}
				$setInsert = M('SpreadEntity')->add(array(
								'spread_title' => I('post.ts') == 'type1' ? I('post.title') : I('post.contents'),
								'spread_file' => I('post.ts') == 'type1' ? I('post.voice_url') : $urlData,
								'res_id' => getLoginMsg()->rid,
								'add_at' => time()
							));
				if($setInsert){
					$this->showtips('操作成功');
				}else{
					$this->showtips('操作失败');
				}
			}else{
				$this->showtips('非法参数');
			}
			$addId = M('SysMsg')->add(array(
					'sys_msg_title' => I('post.title'),
					'sys_msg_content' => I('post.contents'),
					'sort' => 0,
					'add_at' => time(),
					'update_at' => time(),
					'editor' => getLoginMsg()->rid
				));
			if($addId){
				putlog('添加推送消息 ID`'.$addId.'`','SysmsgController','addmsg');
				$this->showtips('添加推送成功');
			}else{
				$this->showtips('操作失败');
			}
		}
		
		$this->display('sysmsg/addmsg');
	}
	
	/*
	 * 年糕妈妈_推送编辑
	 * @date: 2015-4-1下午3:05:42
	 * @editor: XING
	 */
	public function delemsg(){
		//暂时不允许删除
	}
	
	/*
	 * 年糕妈妈_日志功能
	 * @date: 2015-4-2下午2:09:00
	 * @editor: XING
	 */
	public function showlogs(){
		/*参数初始化*/
		$page = I('get.page',1);
		$perpage = 10;$url = '';
		$getResList = M('ResEntity')->where(array('is_active'=>'1'))->select();
		$list = M('SysLogs');
		if(I('get.rid')){
			$list = $list->where(array('sys_editor'=>I('get.rid')));
			$url['rid'] = I('get.rid');
		}
		if(I('get.dotime')){
			$list = $list->where('add_at > '.strtotime(I('get.dotime')).' AND add_at < '.(strtotime(I('get.dotime'))+24*3600));
			$url['dotime'] = I('get.dotime');
		}
		
		$getObj = clone $list;
		$sysData = $list->order(array('sys_action_id'=>'desc'))->page($page,$perpage)->select();
		$this->assign('page',setPage($getObj->count(),$perpage,$page,'?'.http_build_query($url)));
		$this->assign('sysData',$sysData);
		$this->assign('getResList',$getResList);
		$this->display('sysmsg/logs');
	}

	/**
	 * 系统推送
	 */
	public function msgPush(){
		$page 		= I('get.page',1);
		$perpage 	= 10;
		$url 		= [];
		$stime   	= I('get.stime');
        $etime   	= I('get.etime');
		$list 		= M('PushEntity');
		if(I('get.push_title')){
			$list = $list->where('push_title LIKE "%'.I('get.push_title').'%"');
			$url['push_title'] = I('get.push_title');
		}
		if(in_array(I('get.push_type'), ['0','1'])){
			$list = $list->where(['push_type'=>I('get.push_type')]);
			$url['push_type'] = I('get.push_type');
		}
		if(I('get.push_id')){
			$list = $list->where(['push_id'=>I('get.push_id')]);
			$url['push_id'] = I('get.push_id');
		}
		//时间筛选
        if($stime && !$etime){
            $list = $list->where(['add_at'=>['gt',strtotime($stime)]]);
            $url['stime'] = $stime;
        }elseif (!$stime && $etime) {
            $list = $list->where(['add_at'=>['lt',strtotime($etime)]]);
            $url['etime'] = $etime;
        }elseif ($stime && $etime) {
            $list = $list->where(['add_at'=>['between',[strtotime($stime),strtotime($etime)]]]);
            $url['stime'] = $stime;
            $url['etime'] = $etime;
        }
		$getObj = clone $list;
		$data = $list->order(['add_at'=>'desc'])->page($page,$perpage)->select();
		$this->assign('page',setPage($getObj->count(),$perpage,$page,'?'.http_build_query($url)));
		$this->assign('data',$data);
		$this->display('sysmsg/msgpush');
	}

	/**
	 * 添加推送消息
	 */
	public function addPush(){
		if(I('post.dosubmit')){
			$push_content 	= trim(I('post.push_content'));
			$push_title 	= trim(I('post.push_title'));
			$push_to 		= trim(I('post.push_to'));
			$push_platform_type = trim(I('post.push_platform_type'));
			$data = [
				'push_title'	=> $push_title,
				'push_content'	=> $push_content,
				'push_after'	=> trim(I('post.push_after'))?:'go_app',
				'push_type'		=> trim(I('post.push_type')),
				'push_to'		=> trim(I('post.push_type'))?$push_to:'all',
				'add_at'		=> time(),
				'update_at'		=> time()
			];
			$add = M('PushEntity')->add($data);
			if($add){
				//调用友盟推送消息
				if(trim(I('post.push_type'))){
					//指定用户
					if($push_platform_type == '1'){
						umeng_push('582e55f51061d25205002538','rflibljnpwonibdkogykahkd2bliubta','ios',$push_to,$push_title,$push_content);
					}else{
						umeng_push('582a6bb55312dd8ba20009f6','e0hv0aby0ehcqnveboa70soykbmgoapu','android',$push_to,$push_title,$push_content);
					}
				}else{
					//所有用户
					try {
						umeng_push('582a6bb55312dd8ba20009f6','e0hv0aby0ehcqnveboa70soykbmgoapu','android','',$push_title,$push_content);
					} catch (Exception $e) {
						
					}
					try {
						umeng_push('582e55f51061d25205002538','rflibljnpwonibdkogykahkd2bliubta','ios','',$push_title,$push_content);
					} catch (Exception $e) {

					}
				}
				$this->showtips('推送成功');
			}else{
				$this->showtips('推送失败');
			}
		}
		$this->display('sysmsg/addpush');
	}

	/**
	 * 删除推送信息
	 */
	public function delPush(){
		if(I('get.id')){
			$del = M('PushEntity')->where(['push_id'=>I('get.id')])->delete();
			if($del){
				$this->showtips('删除成功');
			}else{
				$this->showtips('删除失败');
			}
		}
	}
}